package com.kaibes.web.security.core;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.kaibes.core.base.util.StringUtils;

public class TokenAuthorizationFilter extends OncePerRequestFilter {
	
	public final static String BEARER = "Bearer ";
	private Token2authentication token2authentication;
	
	public TokenAuthorizationFilter(Token2authentication token2authentication) {
	    this.token2authentication = token2authentication;
    }
	
	@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    	String authorization = request.getHeader("authorization");
    	if (authorization!=null && !authorization.startsWith(BEARER)) {
    		authorization = null;
		}
    	
    	if (StringUtils.isBlankOrNotStartsWith(authorization, BEARER)) {
    		Cookie[] cookies = request.getCookies();
        	if (cookies != null) {
    			for (Cookie cookie : cookies) {
    				if (cookie.getName().equals("token")) {
    					authorization = cookie.getValue();
    				}
    			}
    		}
		} else {
			authorization = authorization.substring(7);
		}
    	
    	if (token2authentication.token2authentication(response, authorization)) {
    	    chain.doFilter(request, response); 
        }
    }
	
}